package cn.funeralobjects.youtube.dl.extension.utils;

import cn.funeralobjects.youtube.dl.extension.service.DownloadService;

import java.io.*;

/**
 * @author FuneralObjects
 * Create date: 2020/4/9 11:25 AM
 */
public class RunningLogUtils {


    public static Writer getWriter(String id, String format) {
        try {
            return new FileWriter(createIfNotExists(id, format), true);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }


    public static String read(String id, String format) {
        File file = getFile(id, format);
        if (!file.exists() || !file.isFile()) {
            return null;
        }
        BufferedReader bufferedReader = null;
        try {
            bufferedReader = new BufferedReader(new FileReader(file));
            StringBuilder result = new StringBuilder();
            String temp;
            while ((temp = bufferedReader.readLine()) != null) {
                result.append(temp).append(CommonUtils.newLine());
            }
            return result.toString();
        } catch (IOException e) {
            throw new RuntimeException(e);
        } finally {
            try {
                assert bufferedReader != null;
                bufferedReader.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    private static File getFile(String id, String format) {
        return new File(DownloadService.DOWNLOAD_FOLDER_PATH + "/" + id + "/" + format + "/run.log");
    }


    private static File createIfNotExists(String id, String format) throws IOException {
        File file = getFile(id, format);
        if (!file.exists() || !file.isFile()) {
            File parentFolder = file.getParentFile();
            if (!parentFolder.exists() || !parentFolder.isDirectory()) {
                if (!parentFolder.mkdirs()) {
                    throw new RuntimeException("The folder[" + parentFolder.getAbsolutePath() + "] creation failed!");
                }
            }
            if (!file.createNewFile()) {
                throw new RuntimeException("The file[" + file.getAbsolutePath() + "] creation failed!");
            }
        }
        return file;
    }
}
